class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> hash=new HashMap<>();
        for(String x:words){
            hash.put(x,hash.getOrDefault(x,0)+1);
        }
        PriorityQueue<Pair<String,Integer>> heap=new PriorityQueue<>(
            (a,b)->{
                if(a.getValue().equals(b.getValue())){
                    return b.getKey().compareTo(a.getKey());
                }
                return a.getValue()-b.getValue();
            }
        );
        for(Map.Entry<String,Integer> e:hash.entrySet()){
            heap.offer(new Pair<>(e.getKey(),e.getValue()));
            if(heap.size()>k){
                heap.poll();
            }
        }
        List<String> ret = new ArrayList<>();
        while(!heap.isEmpty()){
            ret.add(heap.poll().getKey());
        }
        Collections.reverse(ret);
        return ret;
    }
}